﻿// TC Core Library
// Copyright © 2008-2010 Tommy Carlier
// http://tc.codeplex.com
// License: Microsoft Public License (Ms-PL): http://tc.codeplex.com/license

using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Text;

namespace TC
{
	/// <summary>Represents a context in which <see cref="T:Action"/>-instances can be executed.</summary>
	public interface IExecutionContext
	{
		/// <summary>Executes the specified <see cref="T:Action"/> in this context.</summary>
		/// <param name="action">The <see cref="T:Action"/> to execute.</param>
		void Execute(Action action);
	}

	/// <summary>Provides common functionality related to <see cref="T:IExecutionContext"/>-instances.</summary>
	public static class ExecutionContext
	{
		/// <summary>Gets the <see cref="T:IExecutionContext"/> to execute actions on the thread-pool.</summary>
		#region SuppressMessage
		[SuppressMessage(
			"Microsoft.Security", 
			"CA2104:DoNotDeclareReadOnlyMutableReferenceTypes",
			Justification = "ThreadPoolExecutionContext has no state.")]
		#endregion
		public static readonly IExecutionContext
			ThreadPool = new ThreadPoolExecutionContext();

		#region inner class ThreadPoolExecutionContext

		private sealed class ThreadPoolExecutionContext : IExecutionContext
		{
			void IExecutionContext.Execute(Action action)
			{
				if (action == null) throw new ArgumentNullException("action");
				Execute(action);
			}

			private static void Execute(Action action)
			{
				System.Threading.ThreadPool.QueueUserWorkItem(x => action());
			}
		}

		#endregion
	}
}
